package com.hunlian.makelove.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.R;
import com.hunlian.makelove.bean.CheckPhoneBean;
import com.hunlian.makelove.bean.LookPhoneBean;
import com.hunlian.makelove.bean.PersonDetailBean;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.Constants;
import com.hunlian.makelove.dialog.AcceptRefuseDialog;
import com.hunlian.makelove.dialog.EduDialog;
import com.hunlian.makelove.net.NetVisitCallback;
import com.hunlian.makelove.net.api.AgreeLPServiceVisit;
import com.hunlian.makelove.net.api.CheckPhoneServiceVisit;
import com.hunlian.makelove.net.api.DetailServiceVisit;
import com.hunlian.makelove.net.api.LookPhoneServiceVisit;
import com.hunlian.makelove.tools.MyToast;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DetailActivity extends BaseActivity implements AcceptRefuseDialog.AgreeBtnInf{

    private DetailActivity mActivity;

    private ImageButton mIbBack;
    private SimpleDraweeView mIvPhoto;
    private TextView mTvName;
    private TextView mTvId;
    private TextView mTvPhone;
    private TextView mTvBirthday;
    private TextView mTvSex;
    private TextView mTvEdu;
    private TextView mTvHeight;
    private TextView mTvProvince;

    private TextView mTvJob;
    private TextView mTvIncome;
    private TextView mTvMarriage;
    private TextView mTvLive;
    private TextView mTvQQ;

    private TextView mTvHobby;
    private TextView mTvCharacter;
    private TextView mTvIntroduce;
    private TextView mTvExpect;

    private LinearLayout mLlBtn;
    private Button mBtnAccept;
    private Button mBtnRefuse;
    private Button mBtnApplyPhone;

    private String mOppositeUserId;
    private String mStatus;
    private String mFrom;
    private boolean mHasSendRequestPhone;
    private PersonDetailBean mPersonDetailBean;
    private AcceptRefuseDialog mAcceptRefuseDialog;
    private CheckPhoneBean checkPhoneBean;
    private boolean applyCheckPhone = false;//申请查看
    private final String CHECK_PHONE = "查看电话";

    @BindView(R.id.tvInfo)
    TextView tvInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        mActivity = this;
        mOppositeUserId = getIntent().getStringExtra("tarId");
        mStatus = getIntent().getStringExtra("status");
        mFrom = getIntent().getStringExtra("from");
        mHasSendRequestPhone = getIntent().getBooleanExtra("hasSendRequestPhone",false);

        initView();
        judgeStatus();

        setListener();
        request();

        mAcceptRefuseDialog = new AcceptRefuseDialog();
        mAcceptRefuseDialog.setAgreeBtnInf(this);
    }

    /**
     *根据状态来判断是否显示功能按钮
     *@author zealjiang
     *@time 2016/6/7 12:57
     */
    private void judgeStatus(){

        if(mFrom==null){
            Toast.makeText(this,"DetailActivity mFrom cannot be null",Toast.LENGTH_SHORT).show();
            return;
        }
        if("yuanfen".equals(mFrom)){
            mLlBtn.setVisibility(View.GONE);
            mBtnApplyPhone.setVisibility(View.VISIBLE);

            if(mHasSendRequestPhone){//如果已经发送过求电话
                mBtnApplyPhone.setVisibility(View.GONE);
            }
        }else if("yaoqingwo".equals(mFrom)){
            mBtnApplyPhone.setVisibility(View.GONE);

            if("0".equals(mStatus)){//去处理
                mLlBtn.setVisibility(View.VISIBLE);
            }else if("1".equals(mStatus)){//已同意
                mLlBtn.setVisibility(View.GONE);
            }else if("2".equals(mStatus)){//已拒绝
                mLlBtn.setVisibility(View.GONE);
            }else{
                mLlBtn.setVisibility(View.GONE);
            }
        }else if("woyaoqing".equals(mFrom)){
            mLlBtn.setVisibility(View.GONE);
            mBtnApplyPhone.setVisibility(View.GONE);
        }


    }

    private void initView() {

        //title
        mIvPhoto = (SimpleDraweeView) findViewById(R.id.iv_head);


        mIbBack = (ImageButton)findViewById(R.id.back);
        mTvName = (TextView)findViewById(R.id.tv_name);
        mTvId = (TextView)findViewById(R.id.tv_id);
        mTvPhone = (TextView)findViewById(R.id.tv_phone);
        mTvPhone.setEnabled(false);

        mTvBirthday = (TextView)findViewById(R.id.tv_birthday);
        mTvSex = (TextView)findViewById(R.id.tv_sex);
        mTvEdu = (TextView)findViewById(R.id.tv_edu);
        mTvHeight = (TextView)findViewById(R.id.tv_height);
        mTvProvince = (TextView)findViewById(R.id.tv_province);

        mTvJob = (TextView)findViewById(R.id.tv_job);
        mTvIncome = (TextView)findViewById(R.id.tv_income);
        mTvMarriage = (TextView)findViewById(R.id.tv_marriage);
        mTvLive = (TextView)findViewById(R.id.tv_live);
        mTvQQ = (TextView)findViewById(R.id.tv_qq);

        mTvHobby = (TextView)findViewById(R.id.tv_hobby);
        mTvCharacter = (TextView)findViewById(R.id.tv_character);
        mTvIntroduce = (TextView)findViewById(R.id.tv_intro);
        mTvExpect = (TextView)findViewById(R.id.tv_expect);

        mLlBtn = (LinearLayout)findViewById(R.id.ll_btn);
        mBtnAccept = (Button)findViewById(R.id.btn_accept);
        mBtnRefuse = (Button)findViewById(R.id.btn_refuse);
        mBtnApplyPhone = (Button)findViewById(R.id.btn_apply_phone);
    }

    private void setListener(){

        mBtnApplyPhone.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(mBtnApplyPhone.getTag()!=null&&mBtnApplyPhone.getTag().equals("sended")){
                    //已经发送求电话
                }else {
                    requestLookPhone(mOppositeUserId);
                }
            }

        });

        mBtnAccept.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                mAcceptRefuseDialog.showDialog(mActivity);
            }

        });

        mBtnRefuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request(mOppositeUserId,"false");
            }
        });

        mIbBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });

        mIvPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mActivity, SpaceImageDetailActivity.class);
                if(mPersonDetailBean!=null){
                    intent.putExtra("url", mPersonDetailBean.getPhoto());
                }
                startActivity(intent);
                overridePendingTransition(R.anim.right_in, R.anim.left_out);
            }
        });

        mTvPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sPhone = mTvPhone.getText().toString();
                if(CHECK_PHONE.equals(sPhone)){//查看电话
                    /**
                     * 显示查看电话，如果还有查看机会，就显示电话号码，如果没有，提示：您的查看机会还有0次，申请查看机会，
                     * 显示“申请查看机会”，点击会跳到一个html页面，里面有申请的流程
                     * 判断是否还有机会查看对方电话
                     */
                    requestCheckPhoneChance();
                }else if(applyCheckPhone){//没有查看机会，申请查看
                    Intent intent = new Intent(mActivity,WebActivity.class);
                    intent.putExtra("title","申请流程");
                    intent.putExtra("url",(String)mTvPhone.getTag());
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_in, R.anim.left_out);
                }
            }
        });
    }

    private void request() {
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }

        createProgressDialog(mActivity);
        progressDialog.show();

        DetailServiceVisit visit = new DetailServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId(),mOppositeUserId);
        //System.out.println("用户详情请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<PersonDetailBean,Object>(mActivity) {

            @Override
            public void onSuccess(PersonDetailBean data) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (data == null) return;
                mPersonDetailBean = data;
                refreshView();
            }

            @Override
            public void onFailure(String errorEvent, String message,Object obj) {
                super.onFailure(errorEvent, message,obj);
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

        });

    }

    private void refreshView(){
        if(mPersonDetailBean==null)return;
        if(mPersonDetailBean.getPhoto()!=null){
            mIvPhoto.setImageURI(Uri.parse(mPersonDetailBean.getPhoto()));
        }

        mTvName.setText(mPersonDetailBean.getNickname());
        mTvId.setText("ID:"+mOppositeUserId);
        mTvBirthday.setText("生日："+mPersonDetailBean.getBirth());
        mTvSex.setText("性别："+mPersonDetailBean.getSex());
        mTvEdu.setText("学历："+mPersonDetailBean.getXueli());
        mTvHeight.setText("身高："+mPersonDetailBean.getHeight());
        mTvProvince.setText("备选省份："+mPersonDetailBean.getBeixuan());


        mTvJob.setText("职业："+mPersonDetailBean.getJob());
        mTvIncome.setText("收入："+mPersonDetailBean.getShouru());
        mTvMarriage.setText("婚姻状况："+mPersonDetailBean.getHunyin());
        mTvLive.setText("现居住地：" + mPersonDetailBean.getAddress());

        String state = mPersonDetailBean.getIfagree();

        if(state.equals("2")){//表示对方同意查看电话
            String phone = mPersonDetailBean.getPhone();

             //phone这行字，有2种处理方式。第一，直接显示电话，不能点击，第二，显示“查看电话”，
             //点击发请求是否有查看机会，有显示电话，没有显示“申请查看”第三，显示“申请查看”，
             //点击申请查看，跳到链接网页

             //如果phone为-1，表示显示 “查看电话”；如果为电话号码显示电话号码
            mTvPhone.setVisibility(View.VISIBLE);
            if("-1".equals(phone)){
                mTvPhone.setText(CHECK_PHONE);
                mTvPhone.setEnabled(true);
                mTvPhone.setBackgroundResource(R.drawable.btn_login_lr_selector);
                mTvPhone.setTextColor(Color.WHITE);

            }else{
                mTvPhone.setText("电话："+mPersonDetailBean.getPhone());
                mTvPhone.setEnabled(false);
                mTvPhone.setBackgroundResource(0);
                mTvPhone.setTextColor(getResources().getColor(R.color.base_pink_color));
            }
        }else{
            mTvPhone.setVisibility(View.GONE);
        }


        mTvHobby.setText(mPersonDetailBean.getHobby());
        mTvCharacter.setText(mPersonDetailBean.getCharactor());
        mTvIntroduce.setText(mPersonDetailBean.getIntroduce());
        mTvExpect.setText(mPersonDetailBean.getExpect());

    }

    /**
     * 求电话
     * @author zealjiang
     * @time 2016/6/28 12:52
     */
    private void requestLookPhone(String oppositeUserId){
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }

        createProgressDialog(mActivity);
        progressDialog.show();

        LookPhoneServiceVisit visit = new LookPhoneServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId(),oppositeUserId);
		//System.out.println("求电话请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<LookPhoneBean,LookPhoneBean>(mActivity){

            @Override
            public void onSuccess(LookPhoneBean data) {
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                AppConfig.eduState = 1;
                Toast.makeText(mActivity, "发送成功", Toast.LENGTH_SHORT).show();
                mBtnApplyPhone.setText("已求电话");
                mBtnApplyPhone.setTag("sended");
                Constants.DETAIL_REQUEST_PHONE = true;
            }

            @Override
            public void onFailure(String errorEvent, String message,LookPhoneBean obj) {
                //super.onFailure(errorEvent, message,obj);
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                if(obj==null){
                    MyToast.showShort(message);
                    return;
                }
                AppConfig.eduState = obj.getEduState();
                if(AppConfig.eduState==0||AppConfig.eduState==3){
                    EduDialog eduDialog = new EduDialog();
                    eduDialog.showDialog(mActivity, message, new EduDialog.AgreeBtnInf() {
                        @Override
                        public void ok() {
                            mActivity.startActivity(new Intent(mActivity, FurtherInfoSubmitActivity.class));
                        }
                    });
                }else{
                    MyToast.showShort(message);
                }
            }

        });
    }


    /**
     * 同意/拒绝对方查看电话请求
     * @author zealjiang
     * @time 2016/6/22 19:02
     */
    private void request(final String oppositeUserId, final String agreeOrNot){
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }

        createProgressDialog(mActivity);
        progressDialog.show();

        AgreeLPServiceVisit visit = new AgreeLPServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId(),oppositeUserId,agreeOrNot);
        //System.out.println("同意/拒绝对方查看电话请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<String,Object>(mActivity){

            @Override
            public void onSuccess(String data) {
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }

                if("true".equals(agreeOrNot)){
                    Toast.makeText(mActivity,"已同意",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(mActivity,"已拒绝",Toast.LENGTH_SHORT).show();
                }

                //返回列表
                mActivity.finish();
            }

            @Override
            public void onFailure(String errorEvent, String message,Object obj) {
                super.onFailure(errorEvent, message,obj);
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }

        });
    }

    /**
     * 请求是否有查看电话的机会
     * @author zealjiang
     * @time 2016/12/20 10:33
     */
    private void requestCheckPhoneChance() {
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }

        createProgressDialog(mActivity);
        progressDialog.show();

        CheckPhoneServiceVisit visit = new CheckPhoneServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId(),mOppositeUserId);
        visit.getResult(new NetVisitCallback<CheckPhoneBean,Object>(mActivity) {

            @Override
            public void onSuccess(CheckPhoneBean data) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (data == null) return;
                checkPhoneBean = data;
                handleCheckPhone();
            }

            @Override
            public void onFailure(String errorEvent, String message,Object obj) {
                super.onFailure(errorEvent, message,obj);
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

        });

    }

    private void handleCheckPhone(){
        /**
         *  显示查看电话，如果还有查看机会，就显示电话号码，如果没有，提示：您的查看机会还有0次，申请查看机会，
         *  显示“申请查看机会”，点击会跳到一个html页面，里面有申请的流程
         */
        if(checkPhoneBean!=null){
            mTvPhone.setVisibility(View.VISIBLE);
            String phone = checkPhoneBean.getPhone();
            if(!TextUtils.isEmpty(phone)){
                //显示电话号码
                mTvPhone.setText("电话："+phone);
                mTvPhone.setEnabled(false);
                mTvPhone.setBackgroundResource(0);
                mTvPhone.setTextColor(getResources().getColor(R.color.base_pink_color));
                applyCheckPhone = false;
                tvInfo.setText("");
                tvInfo.setVisibility(View.GONE);
            }else{
                //提示：您的机会还有0次，请申请查看机会
                //MyToast.showShort(checkPhoneBean.getText());
/*                SpannableString spannableString = new SpannableString(checkPhoneBean.getText()+checkPhoneBean.getBtn());
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#3F48CC"));
                spannableString.setSpan(colorSpan, checkPhoneBean.getText().length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                mTvPhone.setText(spannableString);//APPLY_CHECK_PHONE);
                */
                tvInfo.setVisibility(View.VISIBLE);
                tvInfo.setText(checkPhoneBean.getText());
                mTvPhone.setText(checkPhoneBean.getBtn());
                mTvPhone.setEnabled(true);
                mTvPhone.setBackgroundResource(R.drawable.btn_login_lr_selector);
                mTvPhone.setTextColor(Color.WHITE);
                //申请链接地址
                mTvPhone.setTag(checkPhoneBean.getLink());
                applyCheckPhone = true;
            }
        }
    }

    @Override
    public void agree() {
        request(mOppositeUserId,"true");
    }
}
